import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Question, QuestionDocument } from '../schemas/questions/question.schema';
import * as fs from 'fs';
import * as path from 'path';
import { CreateQuestionDto } from './dto/create-question.dto';
const uploadPath = path.resolve(__dirname, '../../uploads');


@Injectable()
export class QuestionsService {
  constructor(
    @InjectModel(Question.name) private questionModel: Model<QuestionDocument>,
  ) {}

  async create(createQuestionDto: CreateQuestionDto): Promise<Question> {
    const createdQuestion = new this.questionModel(createQuestionDto);
    return createdQuestion.save();
  }

  async findOne(id: string): Promise<Question> {
    const question = await this.questionModel.findById(id).exec();
    if (!question) throw new NotFoundException('Question not found');
    return question;
  }

  async update(id: string, updateData: any, files?: Express.Multer.File[]) {
    const question = await this.questionModel.findById(id);
    if (!question) throw new NotFoundException('Question not found');
  
    // 删除旧图片时使用绝对路径
    if (files && files.length > 0) {
      question.imageUrls.forEach(imageUrl => {
        const filename = path.basename(imageUrl);
        const filePath = path.join(uploadPath, filename); // 使用绝对路径
        if (fs.existsSync(filePath)) {
          fs.unlinkSync(filePath);
        }
      });
      // 更新为新图片路径
      question.imageUrls = files.map(file => `/uploads/${file.filename}`);
    }
  
    // 更新其他字段
    Object.assign(question, updateData);
    return question.save();
  }

  async remove(id: string): Promise<{ deleted: boolean }> {
    const question = await this.questionModel.findByIdAndDelete(id);
    if (!question) throw new NotFoundException('Question not found');
    // 删除关联的图片
    question.imageUrls.forEach(imageUrl => {
      const filePath = path.join('./uploads/', path.basename(imageUrl));
      if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
    });
    return { deleted: true };
  }

  async findByMaterialId(materialId: string): Promise<Question[]> {
    return this.questionModel.find({ materialId }).populate('materialId').exec();
  }
  async findByIds(ids: string[]): Promise<Question[]> {
    return this.questionModel.find({ _id: { $in: ids } }).exec(); // 使用 $in 查询多个 ID
  }
}